package org.cocos2dx.javascript;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.vivo.ad.model.AdError;
import com.vivo.ad.splash.SplashAdListener;
import com.vivo.mobilead.manager.VivoAdManager;
import com.vivo.mobilead.model.BackUrlInfo;
import com.vivo.mobilead.splash.SplashAdParams;
import com.vivo.mobilead.splash.VivoSplashAd;
import com.vivo.mobilead.util.VOpenLog;
import com.vivo.unionsdk.open.VivoUnionSDK;


/**
 * @author 11101035
 */
public class BaseSplashActivity extends Activity {
    private static final String TAG = "SplashActivity";
    protected VivoSplashAd vivoSplashAd;
    protected SplashAdParams.Builder builder;
    public boolean canJump = false;
    public AppActivity app = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fetchSplashAd(this);
    }
    /**
     * 获取广告
     *
     * @param activity
     */
    protected void fetchSplashAd(Activity activity) {
        builder = new SplashAdParams.Builder(Config.SplashId);
        // 拉取广告的超时时长：即开屏广告从请求到展示所花的最大时长（并不是指广告曝光时长）取值范围[3000, 5000]
        builder.setFetchTimeout(3000);
        /**
         * 标题最长5个中文字符 描述最长8个中文字符
         */
        builder.setAppTitle(Config.APP_NAME);
        /**
         * 广告下面半屏的应用标题+应用描述:应用标题和应用描述是必传字段，不传将抛出异常
         */
        builder.setAppDesc("娱乐休闲首选游戏");
        String backUrl = "vivobrowser://browser.vivo.com?i=12";
        String btnName = "test";
        builder.setBackUrlInfo(new BackUrlInfo(backUrl, btnName));
        builder.setSplashOrientation(SplashAdParams.ORIENTATION_PORTRAIT);
        loadAd(activity,mSplashAdListener);
    }

    protected void loadAd(Activity activity, SplashAdListener listener) {
        vivoSplashAd = new VivoSplashAd(activity, listener, builder.build());
        vivoSplashAd.loadAd();
    }

    private SplashAdListener mSplashAdListener = new SplashAdListener() {
        @Override
        public void onADDismissed() {
            Log.d(Config.TAG, "闪屏onADDismissed");
          next();
        }

        @Override
        public void onNoAD(AdError error) {
            Log.d(Config.TAG, "没有广告：" + error.getErrorMsg());
            if (vivoSplashAd != null) {
                vivoSplashAd.close();
            }
            toNextActivity();
        }

        @Override
        public void onADPresent() {
            Log.d(Config.TAG, "广告展示成功");
        }

        @Override
        public void onADClicked() {
            Log.d(Config.TAG, "广告被点击");
        }
    };

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当广告被点击，会跳转其他页面，此时开发者还不能打开自己的App主页。当从其他页面返回以后， 才可以跳转到开发者自己的App主页；
     */
    private void next() {
        if (this.canJump) {
            toNextActivity();
        } else {
            this.canJump = true;
        }
    }

    private void toNextActivity() {
       this.finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.canJump) {
            next();
        }
        this.canJump = true;
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，
     * 否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 如果没有READ_PHONE_STATE权限，则可能无法获取到广告
     */
    private void requestPermission() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            boolean havePermission = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
            if (!havePermission) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && hasAllPermissionsGranted(grantResults)) {
            // 开始调用广告组件请求广告
        } else {
            // 如果用户没有授权，那么应该说明意图，引导用户去设置里面授权。
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }
}
